<template>
	<Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row  v-show="!switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="5">
                    <FormItem label="公司名称：" >
                            <Select filterable v-model="form1.itemOrgId"   @on-change="selectItemOrgId" >
                                <Option v-for="item in majorOrgList" :value="item.itemOrgId" :key="item.itemOrgId">{{ item.itemOrgName }}</Option>
                            </Select>
                    </FormItem>
                </Col>
                <Col span="5">
                    <FormItem label="项目大类：" prop="majorId">
                            <Select filterable v-model="form1.majorId"    >
                                <Option v-for="item in majorIdList" :value="item.majorId" :key="item.majorId">{{ item.majorName }}</Option>
                            </Select>
                    </FormItem>
                </Col>
                <Col span="5">
                    <FormItem label="审计内容：" prop="majorId">
                            <Input type="text" v-model="form1.subitemName"/>
                    </FormItem>
                </Col>
                <Col span="5">
                    <Button @click="reset" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
            </Row>

            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addItemInfo">新增项目</Button>
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增审计内容</Button>
                    <!--<Button size="large"  class="ivu-btn-delete" icon="md-trash" @click="batDelete">删除</Button>-->
                </Col>
            </Row>
        </Form>

        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据！" @on-selection-change = 'getSelectRows'
               :loading="buttonLoading" size="small"  border :columns="columns1"  :data="dataTable" >


            <template slot-scope="{ row, index }" slot="subitemName">
                    <Input type="textarea" v-model="edit.subitemName" v-if="edit.editIndex === index"/>
                    <span v-else>{{ row.subitemName }}</span>
            </template>

            <template slot-scope="{ row, index }" slot="subitemStander">
                    <Input type="textarea" v-model="edit.subitemStander" v-if="edit.editIndex === index"/>
                    <span v-else>{{ row.subitemStander }}</span>
            </template>

           <!-- <template slot-scope="{ row, index }" slot="action">
                <div v-if="edit.editIndex === index">
                  <a type="info" style="margin-right: 5px"   size="small" @click="handleSave(index)">保存</a>
                  <a size="small" style="margin-right: 5px; color:red" @click="edit.editIndex = -1">取消</a>
                </div>
                <div v-else>
                    <a size="small" style="margin-right: 5px;fontSize: '14px'" type="primary" @click="showData1(row)">详情</a>
                    <a size="small" style="margin-right: 5px;fontSize: '14px'" type="primary" @click="handleEdit(row, index)">修改</a>
                    <a size="small" style="margin-right: 5px;fontSize: '14px';color:red"   @click="removeTemp(row)">删除</a>
                </div>
              </template>-->
        </Table>


        <Row style="margin-right:10px;">
            <Col span="24" >
                    <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>

        <Modal  title="新增审计项目内容" :transfer=false v-model="model1"  :width=800 >
                    <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom"  label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="项目大类：" prop="majorId">
                                    <Select filterable v-model="form1datacopy.majorId"  @on-change="selectCodingSort1"  >
                                        <Option v-for="item in majorIdList" :value="item.majorId" :key="item.majorId">{{ item.majorName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="项目名称：" prop="itemId" >
                                    <Select filterable v-model="form1datacopy.itemId"  @on-open-change="selectCodingSort"  >
                                        <Option v-for="item in itemIdList" :value="item.itemId" :key="item.itemId">{{ item.itemName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="总分值：" prop="itemScore">
                                    <Input type="text" v-model="form1datacopy.itemScore" ></Input>
                                </FormItem>
                            </Col>
                             <Col span="11">
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="总体评价标准：" >
                                    <Input v-model="form1datacopy.assessStander" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="3">
                                <p class="tableTitle">审计内容</p>
                            </Col>
                            <Col span="3" offset="16">
                                <Button type="primary"  class='ivu-btn-save' @click="addRow" >新增</Button>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <Table   class="tableClass"  highlight-row stripe border
                                    width="100%" :columns="modelColumns" :data="form1datacopy.subItemDetails">
                                </Table>
                            </Col>
                        </Row>
                        <!--
                        <Row type="flex" justify="center" class="code-row-bg">
                            <Col span="23" >
                                <FormItem>
                                    <Button type="primary"  class='ivu-btn-save' @click="submit('form1datacopy')" >确定</Button>
                                    <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                                </FormItem>
                            </Col>
                        </Row>-->
                    </Form>
                    <div slot="footer">
                        <Button class='ivu-btn-save' @click="submit('form1datacopy')" >确定</Button>
                        <Button class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                    </div>
        </Modal>

        <Modal  title="新增审计项目内容" :transfer=false v-model="model3"  :width=800>
                    <Form ref="form1ItemData" :model="form1ItemData" :rules="ruleCustom1"  label-position="top">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="项目大类：" prop="majorId">
                                    <Select filterable v-model="form1ItemData.majorId"  @on-change="selectCodingSort1"  >
                                        <Option v-for="item in majorIdList" :value="item.majorId" :key="item.majorId">{{ item.majorName }}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label="项目名称：" prop="itemName" >
                                    <Input type="text" v-model="form1ItemData.itemName" ></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" >
                                <FormItem label="总分值：" prop="itemScore">
                                    <Input type="text" v-model="form1ItemData.itemScore" ></Input>
                                </FormItem>
                            </Col>
                             <Col span="11">
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label="总体评价标准：" >
                                    <Input v-model="form1ItemData.assessStander" type="textarea" :rows="2" />
                                </FormItem>
                            </Col>
                        </Row>

                        <!--
                        <Row type="flex" justify="center" class="code-row-bg">
                            <Col span="23" >
                                <FormItem>
                                    <Button type="primary"  class='ivu-btn-save' @click="submit3('form1ItemData')" >确定</Button>
                                    <Button type="primary"  class='ivu-btn-cancel' @click="handleCancel3" >取消</Button>
                                </FormItem>
                            </Col>
                        </Row>-->
                    </Form>
                    <div slot="footer">
                        <Button class='ivu-btn-save' @click="submit3('form1ItemData')" >确定</Button>
                        <Button class='ivu-btn-cancel' @click="handleCancel3" >取消</Button>
                    </div>
        </Modal>
        <Modal title="查看审计项目内容" v-model="model2"  :width=800 >
           
                    <Form  :model="showdata" :label-width="160" >
                        <Row type="flex" justify="space-around" class="detail-background-clor">
                            <Col span="11" >
                                <FormItem label="项目大类名称：">
                                    {{showdata.majorName}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                                <FormItem label="项目名称："  >
                                     {{showdata.itemName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="11" >
                                <FormItem label="项目分值：">
                                    {{showdata.itemScore}}
                                </FormItem>
                            </Col>
                            <Col span="11" >
                               
                            </Col>
                        </Row>
                        
                        <Row type="flex" justify="space-around" class="detail-background-clor">
                            <Col span="23">
                                <FormItem label="审计内容：" prop="planStartTime">
                                    {{showdata.subitemName}}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" >
                            <Col span="23">
                                <FormItem label="审计标准：" prop="notes">
                                    {{showdata.subitemStander}}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    
                    <div slot="footer">
                        <Button @click="onCancel"  class='ivu-btn-save'>关闭</Button>
                    </div>
        </Modal>
	</layout>
</template>

<script>
    import Vue from 'vue'
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    var cascaderDom = () => import('@/components/cascader-dom.vue');
	export default {
        components: {
            
        },
        props: ['templateTypeCode'],
		data() {
			return {
                edit: {
                    editIndex: -1 // 当前聚焦的输入框的行数
                },
                //templateTypeCode: '',
                majorOrgList:[],
			    switchFlag : false,
				form1: {
				},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
				columns1: [
				    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                     {  minWidth: 200,
						title: '项目大类名称',
						key: 'majorName',
						align: 'center'
                    },
                     {  minWidth: 150,
						title: '项目名称',
						key: 'itemName',
						align: 'center'
                    },
                    {
                        minWidth: 400,
						title: '审计内容',
						key: 'subitemName',
                        align: 'center',
                        slot: 'subitemName'
                    },
                    {
                        minWidth: 400,
						title: '评价标准',
						key: 'subitemStander',
                        align: 'center',
                        slot: 'subitemStander'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 200,
                        align: 'center',
                        // slot: 'action',
                        render: (h, params) => {
                            if (params.index == this.edit.editIndex) {
                                return h('div', [
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleSave(params.index);
                                            }
                                        }
                                    },'保存'),
                                    h('Divider', {
                                        props: {
                                            type: 'vertical',
                                        }
                                    }, ''),
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px'
                                        },
                                        on: {
                                            click: () => {
                                                this.edit.editIndex = -1
                                            }
                                        }
                                    },'取消')
                                ]);
                            }else {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData1(params.row);
                                        }
                                    }
                                },'详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.handleEdit(params.row,params.index);
                                        }
                                    }
                                },'修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type : "ios-trash",
                                        size : 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red',
                                    },
                                    on: {
                                        click: () => {
                                            this.removeTemp(params.row);
                                        }
                                    }
                                },'删除')
                            ]);
                        }}
                    }
                ],
                modelColumns: [ 
                    {
                        title: '序号',
                        key: 'subitemSeq',
						minWidth: 80,
						align: 'center',
                    },
                    {
                        minWidth: 330,
						title: '审计内容',
						key: 'subitemName',
                        align: 'center',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'textarea',
                                    value: params.row.subitemName
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.subitemName = event.target.value;
                                        this.form1datacopy.subItemDetails[params.row.subitemSeq -1 ] = params.row;
                                    }
                                }
                            })
                        }
                    },
                    {
                        minWidth: 250,
						title: '评价标准',
						key: 'subitemStander',
                        align: 'center',
                        render: (h, params) => {
                            return h('Input', {
                                props: {
                                    type: 'textarea',
                                    value: params.row.subitemStander
                                },
                                on: {
                                    'on-change': (event) => {
                                        params.row.subitemStander = event.target.value;
                                        this.form1datacopy.subItemDetails[params.row.subitemSeq -1 ] = params.row;
                                    }
                                }
                            })
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        align: 'center',
                        fixed: 'right',
                        minWidth: 80,
                        render: (h, params) => {
                            return h('div', [
                                h('Icon', {
                                    props: {
                                        type: "ios-trash",
                                        size: '20'
                                    },
                                    style: {
                                        marginRight: "0px"
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteDetail(params.index);
                                        }
                                    }
                                })
                            ]);
                        }
                    }
                ],
                itemIdList:[],
                majorIdList:[],
                currentOrgId : '',
                currentOrgName: '',
                setCurrentName : {},
                ruleCustom : {
                    majorId: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    itemId: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ]
                },
                ruleCustom1 : {
                    majorId: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    itemName: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    itemScore: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ]
                },
                form1datacopy : {
                    subItemDetails:[]
                },
                form1ItemData : {
                    subItemDetails:[]
                },
                teamTypes:[],
                resLevels:[],
                dataTable: [],
                showdata: {},
                model1: false,
                model2: false,
                model3: false,
                add: false,
                buttonLoading:false,tableHeight : 10,
                deleteRows  : [],
			}
        },
        
        created:function(){
            // this.templateTypeCode = this.$route.query.templateType
            
        },
        
		mounted: function() {
            this.tableHeight = window.innerHeight - 330
            this.selectCodingSort();
            this.query();

        },
		methods: {
            selectItemOrgId(val) {
                let data = {
                    templateTypeCode: this.templateTypeCode,
                    createOrgId : val.value 
                }
                this.$http.get(Api.getAuditTemplateAllMarjorItems, {params:data}).then((res) => {
                    this.majorIdList = res.data.data;
                    //console.log(111,this.itemIdList)
                    
                })
                
            },
            onCancel() {
                this.model2 = false
            },
            handleEdit(row, index) {
                this.edit = {...this.edit,...row}
                this.edit.editIndex = index;
            },
            deleteDetail(index){
                this.form1datacopy.subItemDetails.splice(index,1);

                this.form1datacopy.subItemDetails.forEach((item,index,array)=>{
                    item.subitemSeq = index + 1
                })
            },
            addRow(){
                // var item = {
                //     minutesMeetingDetailId:"",
                //     planContent:"",
                //     achieveContent:"",
                //     minutesMeetingId:this.form1datacopy.minutesMeetingId,
                //     orgId:"",
                //     sortNum:this.form1datacopy.meetingDetails.length>0?this.form1datacopy.meetingDetails[this.form1datacopy.meetingDetails.length-1].sortNum+1:1
                // }
                let num = this.form1datacopy.subItemDetails.length + 1
                var item = {
                    subitemSeq:num,
                    subitemName:"",
                    subitemStander:''
                }
                this.form1datacopy.subItemDetails.push(item);
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(!this.switchFlag){
                    this.tableHeight = window.innerHeight - 220;
                }else{
                    this.tableHeight = window.innerHeight - 315;
                }
            },
            handleSave(index) {
                this.dataTable[index].subitemName = this.edit.subitemName;
                this.dataTable[index].subitemStander = this.edit.subitemStander;
                this.edit.editIndex = -1;

                this.$http.post(Api.updateAuditTemplateSub, this.dataTable[index]).then((res) => {
                        this.$Message.success("更新成功")
                        this.query();
                }).catch(e => {
                    this.query();
                    this.$Message.error("数据获取失败")
                })
            },
            selectCodingSort1(val) {
                let data = {majorId: val}
                this.$http.get(Api.getAuditTemplateItems, {params:data}).then((res) => {
                    this.itemIdList = res.data.data;

                    // if(this.itemIdList){
                    //    console.log('aaaaaaaaaa',this.itemIdList)
                    // }
                    
                })
                
            },
            selectCodingSort() {
                let data = {
                    templateTypeCode: this.templateTypeCode
                }
                this.$http.get(Api.getAuditTemplatePageInit, {params:data}).then((res) => {
                    this.majorOrgList = res.data.data;
                    if(this.majorOrgList){
                        //this.majorIdList.unshift({majorId:-1,majorName:"全部"})
                    }
                })

                // this.$http.get(Api.queryCodeDetailBySortId + '/STY-000011', {params: {}}).then((res) => {
                //     this.teamTypes = res.data.data;
                // })
                // this.$http.get(Api.queryCodeDetailBySortId + '/RL-000011', {params: {}}).then((res) => {
                //     this.resLevels = res.data.data;
                // })
            },
         
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            showData1(row) {
                    this.showdata = row;
                    this.model2 = true;
            },

            showData(data, flag) {
                this.currentOrgId  = data.row.belongOrgId;
                this.currentOrgName = data.row.belongOrgName;
                this.setCurrentName  = { value :  data.row.contactorId, label :  data.row.contactorName };

                if (flag == 1) {
                    //查看页面
                    this.showdata = data.row;
                    this.showdata.setupDate = this.formatDate(new Date(this.showdata.setupDate), 'yyyy-MM-dd');
                    this.model2 = true;
                } else {
                    //修改页面
                    this.form1datacopy = data.row;
                    this.model1 = true;
                }
            },

            getSelectRows (rows){
                this.deleteRows = rows;
            },
            removeTemp(row){

                this.$Modal.confirm({
                    title: '提示信息',
                    content: '<p>确定删除该条信息</p>',
                    okText:'确认',
                    cancelText:'取消',
                    onOk: () => {
                        let url = Api.deleteAuditTemplateSub + '/'+ row.subitemId;
                        this.$http.get(url, {}).then((res) => {
                            this.$Message.success('成功');
                            this.query()
                        }).catch(e => {
                            this.$Message.error('请求失败' + e);
                        })
                    }
                })
                
            },
            deleteData(params) {
                let url = Api.deleteGroupMeet;
                this.$http.get(url, {params: {objId :  params.row.id}}).then((res) => {
                    this.$Message.success('成功');
                    this.query()
                }).catch(e => {
                    this.$Message.error('请求失败' + e);
                })
            },

            query() {this.buttonLoading=true
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    templateTypeCode: this.templateTypeCode,
                }

                let itemOrgId12 =  sessionStorage('userId').getObject('userId').companyId;


                data.createOrgId = this.form1.itemOrgId || itemOrgId12 
                data.majorId = this.form1.majorId || '' 
                data.subitemName = this.form1.subitemName || '' 
                let url = Api.queryAuditTemplate;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;this.buttonLoading=false
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {}
            },
            handleCancel3() {
                this.form1ItemData = {};
                this.model3 = false;
            },
            handleCancel() {
                this.form1datacopy = {};
                this.model1 = false;
            },
            submit3(name) {
                this.$refs[name].validate((valid) => {
                     if (valid) {
                        this.$http.post(Api.createAuditTemplateItem, this.form1ItemData).then((res) => {
                            this.$Message.success("保存成功")
                            this.model3 = false;
                            this.query();

                        }).catch(e => {
                            this.model3 = false;
                            this.query();
                            this.$Message.error("数据获取失败")
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            submit(name) {
                this.$refs[name].validate((valid) => {
                     if (valid) {
                        
                        if(!this.form1datacopy.subItemDetails || this.form1datacopy.subItemDetails.length === 0){
                            this.$Message.warn("请添加审计内容")
                            return 
                        }

                        this.$http.post(Api.createAuditTemplate, this.form1datacopy).then((res) => {
                            this.$Message.success("保存成功")
                            this.model1 = false;
                            this.query();

                        }).catch(e => {
                            this.model1 = false;
                            this.query();
                            this.$Message.error("数据获取失败")
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            addItemInfo() {
                this.form1datacopy = {};
                this.model3 = true;
            },
            addInfo() {
                this.form1datacopy = {};
                Vue.set(this.form1datacopy, 'subItemDetails', [])
                
                this.model1 = true;
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
        watch:{
            // $route(){
            //     this.templateTypeCode = this.$route.query.templateType
            //     this.selectCodingSort();
            //     this.query()
            // },
            "model1":function(qw,er){
                if(qw && this.model1){
                    setTimeout(()=>{
                        //this.$refs.carOrg.setCurrentOrg();
                        //this.$refs.childUser.setCurrentUser();
                    },100)
                }else{
                    //this.$refs.carOrg.setCurrentOrg();
                    //this.$refs.childUser.setCurrentUser();
                }
            },

        },
	}
</script>
<style scoped>
    @import '../../../index.css';
</style>
